package com.jy.api.service.impl;

import com.jy.api.dao.CashCouponDao;
import com.jy.api.dao.EmployeeDao;
import com.jy.api.domain.CashCoupon;
import com.jy.api.domain.Employee;
import com.jy.api.service.CashCouponService;
import com.jy.api.signUpReq.admin.CashCouponReq;
import com.jy.api.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Principal;
import java.util.List;

/**
 * Created by xiaohua on 2019/1/18.
 */
@Service
public class CashCouponServiceImpl implements CashCouponService {

    @Autowired
    private CashCouponDao cashCouponDao;
    @Autowired
    private EmployeeDao employeeDao;

    @Override
    @Transactional
    public Result addCashCoupon(CashCouponReq req, Principal principal) {

        Employee employee = employeeDao.findByStoreIdAndUsernameAndEnabled(req.getStoreId(),
                principal.getName(), true);
        CashCoupon cashCoupon = new CashCoupon(req, employee);
        cashCouponDao.save(cashCoupon);
        return new Result(200, "代金券添加成功");
    }

    @Override
    public List<CashCoupon> findAllCoupon(String storeId) {
        List<CashCoupon> list = cashCouponDao.findByStoreIdAndEnabledOrderByAddTimeDesc(storeId, true);
        return list;
    }

    @Override
    @Transactional
    public Result updateCouponById(CashCouponReq req) {
        CashCoupon cashCoupon = cashCouponDao.findOne(req.getId());
        cashCoupon.updateCashCoupon(cashCoupon, req);
        cashCouponDao.save(cashCoupon);
        return new Result(200, "代金券修改成功");
    }

    @Override
    @Transactional
    public Result deleteCouponById(CashCouponReq req) {
        CashCoupon cashCoupon = cashCouponDao.findOne(req.getId());
        if (null == cashCoupon) {
            return new Result(400, "该代金券不存在");
        } else {
            cashCoupon.setEnabled(false);
            cashCouponDao.save(cashCoupon);
            return new Result(200, "删除成功");
        }

    }
}
